<?php

class NewsController extends Controller {

	/**
	 * @var string the default layout for the views. Defaults to
	 * '//layouts/column2', meaning using two-column layout. See
	 * 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';

	/**
	 * Declares class-based actions.
	 */
	public function actions() {
		return array(
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
		);
	}

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array(
				'allow',
				'actions'=>array(
					'captcha',
					'index',
					'create',
					'view',
					'monitor',
					'monitoring',
					'download',
				),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array(
					'update',
					'hide',
					'unhide',
					'sticky',
					'unsticky',
					'admin',
					'delete',
					'blacklist',
				),
				'users'=>array('@'),
			),
			array('deny', // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$this->render('view', array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view'
	 * page.
	 */
	public function actionCreate() {
		if (Yii::app()->theme->name != 'mobile') {
			$this->redirect(array('index'));
		}

		$model = new MobileWebNews;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['MobileWebNews'])) {
			$model->attributes = $_POST['MobileWebNews'];
		}

		if (isset($_POST['MobileWebNews'])) {
			if ($model->save()) {
				$this->redirect(array('index', 'id'=>$model->_id));
			}
		}

		$this->render('create', array('model'=>$model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view'
	 * page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		If (!Yii::app()->user->checkAccess('newsUpdate')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$model = $this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		$class = get_class($model);
		if (isset($_POST[$class])) {
			$model->attributes = $_POST[$class];
			if ($model->save()) $this->redirect(array('index'));
		}

		$this->render('update', array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin'
	 * page.
	 *
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		If (!Yii::app()->user->checkAccess('newsDelete')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we
			// should not redirect the browser
			if (!isset($_GET['ajax'])) {
				if (isset($_POST['returnUrl'])) {
					$this->redirect($_POST['returnUrl']);
				} else {
					$this->redirect(array('admin'));
				}
			}
		} else {
			throw new CHttpException(
				400,
				'Invalid request. Please do not repeat this request again.'
			);
		}
	}

	/**
	 * Load data provider.
	 *
	 * @param integer $date Epoch time
	 * @return CActiveDataProvider
	 */
	private function _loadDataProvider($date, $order='DESC') {
		$month = date('n', $date);
		$day = date('j', $date);
		$year = date('Y', $date);
		$start = mktime(0, 0, 0, $month, $day, $year);
		$end = mktime(23, 59, 59, $month, $day, $year);
		$condition = "hidden = 0 AND dateTime BETWEEN $start AND $end";
		$criteria = array(
			'condition'=>$condition,
			'order'=>"dateTime $order",
		);
		$config = array(
			'criteria'=>$criteria,
			'pagination'=>false,
		);
		return new CActiveDataProvider('News', $config);
	}

	protected $_rights = null;

	/**
	 * Load access rights.
	 */
	public function _loadRights() {
		if ($this->_rights === null) {
			$user = Yii::app()->user;
			$this->_rights = array(
				'hide'=>$user->checkAccess('newsHide'),
				'unhide'=>$user->checkAccess('newsUnhide'),
				'sticky'=>$user->checkAccess('newsSticky'),
				'unsticky'=>$user->checkAccess('newsUnsticky'),
				'update'=>$user->checkAccess('newsUpdate'),
				'blacklist'=>$user->checkAccess('newsBlacklist'),
			);
		}
		return $this->_rights;
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex($date=false, $lastUpdate=false) {
		if (!$date) {
			if (isset($_GET['year']) && isset($_GET['month']) &&
				isset($_GET['day'])) {
				$month = $_GET['month'];
				$year = $_GET['year'];
				$day = $_GET['day'];
				$date = mktime(0, 0, 0, $month, $day, $year);
			} else {
				$date = time();
			}
		}

		$this->_ajaxIndex($date, $lastUpdate);

		$dataProvider = $this->_loadDataProvider($date);
		if ($dataProvider->itemCount) {
			$lastUpdate = $dataProvider->data[0]->dateTime;
		} else {
			$lastUpdate = 0;
		}
		$data = array(
			'dataProvider'=>$dataProvider,
			'total'=>$dataProvider->itemCount,
			'date'=>$date,
			'lastUpdate'=>$lastUpdate,
			'rights'=>$this->_loadRights(),
		);
		$this->render('index', $data);
	}

	/**
	 * List all models for Ajax request.
	 * @param integer $date Epoch time
	 * @param integer $lastUpdate Epoch time
	 * @return string ajax response
	 */
	protected function _ajaxIndex($date, $lastUpdate) {
		if (isset($_GET['ajax']) && $_GET['ajax'] === 'news-index') {
			$values = array();
			$total = 0;
			$dataProvider = $this->_loadDataProvider($date);
			$data = $dataProvider->data;
			if ($dataProvider->itemCount) {
				if ($dataProvider->data[0]->dateTime != $lastUpdate) {
					$lastUpdate = $dataProvider->data[0]->dateTime;
					$view = 'application.views.news._view';
					$rights = $this->_loadRights();
					foreach ($data as $model) {
						$data = array(
							'data'=>$model,
							'rights'=>$rights,
							'index'=>$total++,
							'dateFormat'=>'full',
						);
						$values[] = $this->renderPartial($view, $data, true);
					}
				}
			} else {
				$lastUpdate = 0;
			}
			$format = Yii::app()->dateFormatter;
			/* @var $dateHuman string date in human readable format */
			$dateHuman = $format->formatDateTime($date, 'full', null);
			$data = array(
				'lastUpdate'=>$lastUpdate,
				'date'=>$date,
				'dateHuman'=>$dateHuman,
				'total'=>$total,
				'values'=>$values,
			);
			echo json_encode($data);
			Yii::app()->end();
		}
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		If (!Yii::app()->user->checkAccess('newsManage')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$model = new News('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['News'])) $model->attributes = $_GET['News'];

		$data = array(
			'model'=>$model,
			'rights'=>$this->_loadRights(),
		);
		$this->render('admin', $data);
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = News::model()->findByPk((int) $id);
		if ($model === null) {
			throw new CHttpException(404, 'The requested page does not exist.');
		}
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'news-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	/**
	 * Hide news.
	 * @param integer $id
	 */
	public function actionHide($id) {
		If (!Yii::app()->user->checkAccess('newsHide')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->loadModel($id)->hide();
		if (!isset($_GET['ajax'])) {
			if (isset(Yii::app()->request->urlReferrer)) {
				$return = Yii::app()->request->urlReferrer;
			} else {
				$return = array('admin');
			}
			$this->redirect($return);
		}
	}

	/**
	 * Unhide news.
	 * @param integer $id
	 */
	public function actionUnhide($id) {
		If (!Yii::app()->user->checkAccess('newsUnhide')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->loadModel($id)->unhide();
		if (!isset($_GET['ajax'])) {
			if (isset(Yii::app()->request->urlReferrer)) {
				$return = Yii::app()->request->urlReferrer;
			} else {
				$return = array('admin');
			}
			$this->redirect($return);
		}
	}

	/**
	 * Sticky news.
	 * @param integer $id
	 */
	public function actionSticky($id) {
		If (!Yii::app()->user->checkAccess('newsSticky')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->loadModel($id)->sticky();
		if (!isset($_GET['ajax'])) {
			if (isset(Yii::app()->request->urlReferrer)) {
				$return = Yii::app()->request->urlReferrer;
			} else {
				$return = array('admin');
			}
			$this->redirect($return);
		}
	}

	/**
	 * Unsticky news.
	 *
	 * @param integer $id
	 */
	public function actionUnsticky($id) {
		If (!Yii::app()->user->checkAccess('newsUnsticky')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->loadModel($id)->unsticky();
		if (!isset($_GET['ajax'])) {
			if (isset(Yii::app()->request->urlReferrer)) {
				$return = Yii::app()->request->urlReferrer;
			} else {
				$return = array('admin');
			}
			$this->redirect($return);
		}
	}

	/**
	 * Blacklist the model sender.
	 *
	 * @param integer $id the ID of the model to be blacklisted
	 */
	public function actionBlacklist($id) {
		If (!Yii::app()->user->checkAccess('newsBlacklist')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->loadModel($id)->blacklist();
		if (!isset($_GET['ajax'])) {
			if (isset(Yii::app()->request->urlReferrer)) {
				$return = Yii::app()->request->urlReferrer;
			} else {
				$return = array('admin');
			}
			$this->redirect($return);
		}
	}

	/**
	 * Download daily news in Excel format.
	 */
	public function actionDownload() {
//		If (!Yii::app()->user->checkAccess('newsDownload')) {
//			$s = 'You are not authorized to perform this action.';
//			throw new CHttpException(403, $s);
//		}

		$model = new News('download');
		if (isset($_POST['News'])) {
			$model->attributes = $_POST['News'];
			if ($model->validate()) {
				$this->_generateReport($model->date);
			}
		} else {
			$model->date = date('Y-m-d');
		}
		$this->render('download', array('model'=>$model));
	}

	/**
	 * Generate report and send them to browser as attachment.
	 *
	 * @param string $date in yyyy-mm-dd format
	 */
	protected function _generateReport($date) {
		$epoch = strtotime($date);
		$dataProvider = $this->_loadDataProvider($epoch, 'ASC');
		$formatter = Yii::app()->dateFormatter;
		$data = array();
		foreach ($dataProvider->data as $model) {
			$data[] = array(
				'sender'=>$model->senderComplete,
				// Because I save dateTime as Jakarta time GMT+7
				'dateTime'=>date($model->dateTime + (60 * 60 * 7)),
				'value'=>$model->value
			);
		}

		$phpExcelPath = Yii::getPathOfAlias('application.components');
		spl_autoload_unregister(array('YiiBase', 'autoload'));
		include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
		$excel = new PHPExcel();
		$excel->getProperties()->setCreator("Ayamo")
			->setLastModifiedBy("Ayamo")
			->setTitle("Senkom Information Center Report")
			->setSubject("Report")
			->setDescription("Senkom Information Center Report")
			->setKeywords("senkom report")
			->setCategory("Daily Report");
		$sheet = $excel->setActiveSheetIndex(0);
		$formatTime = 'hh:mm';
		$formatDate = 'DDDD, MMMM D, YYYY';
		$sheet->setCellValue("A1", "Laporan Harian Senkom Information Center");
		$time = PHPExcel_Shared_Date::PHPToExcel($epoch + (60 * 60 * 7));
		$sheet->setCellValue("A2", $time);
		$sheet->getStyle("A2")->getNumberFormat()->setFormatCode($formatDate);
		foreach ($data as $key=>$value) {
			$index = $key + 5;
			$time = PHPExcel_Shared_Date::PHPToExcel($value['dateTime']);
			$sheet->setCellValue("A$index", $time);
			$sheet->getStyle("A$index")->getNumberFormat()
				->setFormatCode($formatTime);
			$sheet->setCellValue("B$index", $value['sender']);
			$sheet->setCellValue("C$index", $value['value']);
		}
		$excel->getActiveSheet()->setTitle('Laporan Harian');
		$excel->setActiveSheetIndex(0);
		header('Content-Type: application/vnd.ms-excel');
		$filename = "Laporan $date.xls";
		header("Content-Disposition: attachment; filename=\"$filename\"");
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
		$objWriter->save('php://output');
		Yii::app()->end();
		spl_autoload_register(array('YiiBase', 'autoload'));
	}

	/**
	 * List all models in monitoring mode
	 */
	public function actionMonitor($theme='monitor') {
		Yii::app()->theme = $theme;
		$model = News::model();
		$criteria = new CDbCriteria;
		$criteria->order = 'dateTime DESC';
		$condition = '`dateTime` >= :start AND `hidden` = 0';
		$criteria->condition = $condition;
		$hour = Yii::app()->params['monitor']['time'];
		$start = time() - ($hour * 60 * 60);
		$criteria->params[':start'] = $start;
		$models = $model->findAll($criteria);
		$lastUpdate = $model->lastUpdate;
		$total = $model->count($criteria);
		if (isset($_GET['ajax']) && $_GET['ajax'] === 'news-monitor') {
			$newses = array();
			foreach ($models as $model) {
				$data = array('data'=>$model);
				$newses[] = $this->renderPartial('_viewMonitor', $data, true);
			}
			$data = array(
				'lastUpdate'=>$lastUpdate,
				'total'=>$total,
				'newses'=>$newses,
			);
			echo json_encode($data);
			Yii::app()->end();
		} else {
			$data = array(
				'lastUpdate'=>$lastUpdate,
				'total'=>$total,
				'models'=>$models,
			);
			$this->render('monitor', $data);
		}
	}
	
	public function actionMonitoring() {
		Yii::app()->theme = 'monitoring';
		
		$criteria = new CDbCriteria;
		$criteria->order = 'dateTime DESC';
		$condition = '`dateTime` >= :start AND `hidden` = 0';
		$criteria->condition = $condition;
		$hour = Yii::app()->params['monitor']['time'];
		$start = time() - ($hour * 60 * 60);
		$criteria->params[':start'] = $start;
		
		$model = News::model();
		$models = $model->findAll($criteria);
		$lastUpdate = $model->lastUpdate;
		$total = $model->count($criteria);
		
		$data = array(
			'lastUpdate'=>$lastUpdate,
			'total'=>$total,
			'models'=>$models,
		);
		$this->render('monitoring', $data);
	}

}
